package com.ljj.sms.controller;

import com.aliyuncs.exceptions.ClientException;
import com.ljj.commonutils.R;
import com.ljj.commonutils.RandomUtil;
import com.ljj.sms.service.SmsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/sms/vcode")
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("{phone}")
    public R sentSMS(@PathVariable String phone) throws ClientException {
        String vcode = redisTemplate.opsForValue().get(phone);
        //如果redis中已经存在，不发送直接返回成功
        if(!StringUtils.isEmpty(vcode)){
            return R.ok();
        }
        vcode = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code",vcode);
        if(smsService.sendVcode(param,phone)){
            redisTemplate.opsForValue().set(phone,vcode,5, TimeUnit.MINUTES);
            return R.ok();
        }else{
            return R.error();
        }

    }
}
